<?php
header('Content-Type: application/json; charset=utf-8');

$uploadDir = '../image/uploads/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$file = $_FILES['file'] ?? null;

if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => 0, 'message' => '上传失败']);
    exit;
}

$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowed = ['jpg', 'jpeg', 'png', 'gif'];
$mimeType = mime_content_type($file['tmp_name']);
$allowedMime = ['image/jpeg', 'image/png', 'image/gif'];

if (!in_array($ext, $allowed) || !in_array($mimeType, $allowedMime)) {
    echo json_encode(['success' => 0, 'message' => '仅支持 JPG, PNG, GIF']);
    exit;
}

$filename = uniqid('img_') . '.' . $ext;
$destination = $uploadDir . $filename;

if (!move_uploaded_file($file['tmp_name'], $destination)) {
    echo json_encode(['success' => 0, 'message' => '保存失败']);
    exit;
}

// 生成完整访问路径
$imageUrl = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/bbs/image/uploads/' . $filename;

echo json_encode([
    'success' => 1,
    'file' => ['url' => $imageUrl],
]);
exit;
